from starlette.endpoints import HTTPEndpoint
from database import Session
from dao import DaoBureauWeeklyRepSum, DaoPowerSupplyBureauOperator, DaoPowerSupplyBureauList, DaoAreaList
from starlette.responses import JSONResponse
import logging
from wxpublic import wx_public_message
import config
from sqlalchemy.exc import DBAPIError
import calendar, datetime
import pendulum

class BureauWeeklyRepSumCheck(HTTPEndpoint):

    def __init__(self, scope):
        self._logger = logging.getLogger('WEEK_REP_CHECK')
        return super().__init__(scope)

    async def get(self, request):
        session = Session()
        try:
            bureauid = request.query_params["bureauid"]
            monthnum = request.query_params["monthnum"]
            weeknum = request.query_params["weeknum"]
            return DaoBureauWeeklyRepSum.get_weeklyrep_check_info(session, bureauid, monthnum, weeknum)
        finally:
            session.close()

    async def put(self, request):
        session = Session()
        try:
            dict_bwrs = await request.json()
            bureauid = dict_bwrs.get("bureauid")
            monthnum = dict_bwrs.get("monthnum")
            weeknum = dict_bwrs.get("weeknum")
            DaoBureauWeeklyRepSum.update_weekly_info_check(session, dict_bwrs)
            session.commit()
        except Exception:
            session.rollback()
            return JSONResponse({"result": "0"})
        else:
            from sqlalchemy.exc import SQLAlchemyError
            try:
                # 这里需要根据审核情况推送审核提醒
                # 审核结果推送
                if dict_bwrs['flag'] in ['2', '3']:
                    # 需要提醒，先获取需要提醒的人员OpenID，然后根据状态推送信息
                    from model.ModCompanyOperator import CompanyOperator
                    from model.ModDepartmentVsBureau import DepartmentVsBureau
                    from wxenterprise.wx_enterprise_message import send_to_user
                    target_employees = session.query(CompanyOperator)\
                        .join(DepartmentVsBureau, DepartmentVsBureau.departmentid == CompanyOperator.departmentid)\
                        .filter(DepartmentVsBureau.bureauid == bureauid)\
                        .filter(CompanyOperator.audit_permission == '1')\
                        .filter(CompanyOperator.company_employee == '0')\
                        .all()
                    msg = f'{monthnum[0:7]}月第{weeknum}周周报已被审核退回，请及时修改。'\
                        if dict_bwrs['flag'] == '3'\
                        else f'{monthnum[0:7]}月第{weeknum}周周报已审核通过。'
                    for person in target_employees:
                        send_to_user(person.openid, msg)
            except SQLAlchemyError:
                self._logger.warn(f'审核状态提醒发送失败，未找到目标人员。')
            finally:
                session.rollback()

            if dict_bwrs['flag'] == '2':
                list_operator = DaoPowerSupplyBureauOperator.get_operator_list(session, bureauid)
                bureau_info = DaoPowerSupplyBureauList.get_bureau_info_sent(session, bureauid)
                area_info = DaoAreaList.get_area_info(session, bureau_info.get("area_flag"))
                weekego = f'{monthnum[0:4]}年第{weeknum}期'
                year = monthnum[0:4]
                month = monthnum[5:7]
                # 拼接字符串
                str_pendulum_start=f'{year}-W{weeknum}-1'
                str_pendulum_end = f'{year}-W{weeknum}-7'
                # 获取当月的第一天
                firstDay = pendulum.parse(str_pendulum_start, strict=False)
                lastDay = pendulum.parse(str_pendulum_end, strict=False)
                weekrange = f'{firstDay.strftime("%Y-%m-%d")}至{lastDay.strftime("%Y-%m-%d")}'
                for operator in list_operator:
                    wx_public_message.send_template_message(operator["openid"],
                                            config.TEMPLATE_PERIOD_REPORT,
                                            {
                                                "first": {
                                                    "value": f'您好，{weekego}采集运维周报已生成，请查阅！',
                                                    "color": "#000000"
                                                },
                                                "keyword1": {
                                                    "value": f'{bureau_info.get("name")}供电公司',
                                                    "color": "#1736c0"
                                                },
                                                "keyword2": {
                                                    "value": "采集运维项目部",
                                                    "color": "#1736c0"
                                                },
                                                "keyword3": {
                                                    "value": weekrange,
                                                    "color": "#1736c0"
                                                },
                                                "remark": {
                                                    "value": "您现在可以查阅报告信息了。",
                                                    "color": "#000000"
                                                }
                                            })
            return JSONResponse({"result": "1"})
        finally:
            session.close()


class BureauWeeklyRepSumCheckList(HTTPEndpoint):

    async def get(self, request):
        session = Session()
        try:
            return DaoBureauWeeklyRepSum.get_weeklyrep_check_list(session)
        finally:
            session.close()


class BureauWeeklyRepSumCheckCount(HTTPEndpoint):
    async def get(self, request):
        session = Session()
        try:
            bureauid = request.query_params["bureauid"]
            flagid = request.query_params["flagid"]
            cou = DaoBureauWeeklyRepSum.get_weekcheck_count(session, bureauid, flagid)
            return JSONResponse({"result": cou})
        finally:
            session.close()
